/* eslint-disable linebreak-style */
import React, { PureComponent } from 'react';
import { Card, Form, Icon, Col, Row, Popconfirm, DatePicker, Input, Select, Popover, message, Button } from 'antd';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import PageHeaderLayout from '../../../../layouts/PageHeaderLayout';
import FooterToolbar from '../../../../components/FooterToolbar/index';
import styles from './style.less';
import { getDicByCodeSort } from '../../../../components/common/PateoForm/utils/helper';
import { getDictOptionsByCode , getDicByKey} from '../../../../support/common'

const { Option } = Select;

const fieldLabels = {
  projectId: '项目',
  deviceId: '设备编号',
  iccid: 'ICCID',
  msisdn: 'MSISDN',
  carrierBrand: '运营商品牌',
  simModel: '套餐类型',
  unicomPkgId: '联通套餐ID',
  payType: '支付类型',
  purchaser: '采购商',
  simStatus: '状态',
  activeTime: '激活时间',
  produceDate: '生产日期 ',
  remark: '备注',
};


@connect(state => ({
  simCard: state.simCard,
}))
// @Form.create()
export default class SimCardSave extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.array,
  };
  state = {
    projectIdData: [],
    query: {},
    buttonLoading: false,
  };
  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        query: this.props.location.state.obj,
      });
    }
  }
  formRef = React.createRef();
  componentDidMount() {
    const { dispatch } = this.props;
    if (this.props.location.state) {
      const record = this.props.location.state.data;
      this.formRef.current.resetFields();
      this.formRef.current.setFieldsValue({
        deviceId: record.deviceId,
        iccid: record.iccid,
        msisdn: record.msisdn,
        carrierBrand: record.carrierBrand,
        simModel: record.simModel,
        unicomPkgId: record.unicomPkgId,
        payType: record.payType,
        purchaser: record.purchaser,
        simStatus: record.simStatus === null ? record.simStatus : record.simStatus.toString(),
        sid: record.sid,
        activeTime: record.activeTime,
        produceDate: record.produceDate,
        remark: record.remark,
      });
    } else {
      dispatch({
        type: 'basedata/fetchProject',
        callback: (data) => {
          this.setState({
            projectIdData: data,
          });
        },
      });
    }
  }

  canceladd = () => {
    this.formRef.current.resetFields();
  }
  canceledit = () => {
    const { query } = this.state;
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    dispatch(routerRedux.push({ pathname: '/connectPlat/simCard', state: { query } }));
  }


  render() {
    const { query, buttonLoading } = this.state;
    const simStatusOptions = getDictOptionsByCode(this.context.dicData, 'simStatus');
    const carrierBrandOptions = getDictOptionsByCode(this.context.dicData, 'carrierBrand');
    const simModelOptions = getDictOptionsByCode(this.context.dicData, 'simModel');
    const payTypeOptions = getDictOptionsByCode(this.context.dicData, 'payType');
    const purchaserOptions = getDictOptionsByCode(this.context.dicData, 'purchaser');
    const { dispatch } = this.props;
    const form = this.formRef.current;
    const projectIdData = this.state.projectIdData.map(d =>
      <Option key={d.value}>{d.label}</Option>);
    // const {  getFieldsError } = form;
    const validate = () => {
      console.log(this.formRef);
      this.formRef.current.validateFields().then((values) => {
        // if (!error) {
          this.setState({
            buttonLoading: true,
          });
          const url = values.sid ? 'simCard/edit' : 'simCard/add';
          console.log(values)
          const obj = values;
          if (url === 'simCard/edit') {
            if (values.produceDate) {
              obj.produceDate = new Date(values.produceDate);
            }
            if (values.activeTime) {
              obj.activeTime = new Date(values.activeTime);
            }
          }
          dispatch({
            type: url,
            payload: obj,
            callback: (response) => {
              if (response.statusCode === '0') {
                message.success('操作成功');
                this.formRef.current.resetFields();
                if (url === 'simCard/edit') {
                  dispatch(routerRedux.push({ pathname: '/connectPlat/simCard', state: { query } }));
                } else {
                  dispatch(routerRedux.push('/connectPlat/simCard'));
                }
              } else {
                message.error(response.description, 3);
              }
              this.setState({
                buttonLoading: false,
              });
            },
          });
        // }
      });
    };
    // const getErrorInfo = () => {
    //   const errors = this.formRef.current.getFieldsError();
    //   const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    //   if (!errors || errorCount === 0) {
    //     return null;
    //   }
    //   const scrollToField = (fieldKey) => {
    //     const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
    //     if (labelNode) {
    //       labelNode.scrollIntoView(true);
    //     }
    //   };
    //   const errorList = Object.keys(errors).map((key) => {
    //     if (!errors[key]) {
    //       return null;
    //     }
    //     return (
    //       <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
    //         <Icon type="cross-circle-o" className={styles.errorIcon} />
    //         <div className={styles.errorMessage}>{errors[key][0]}</div>
    //         <div className={styles.errorField}>{fieldLabels[key]}</div>
    //       </li>
    //     );
    //   });
    //   return (
    //     <span className={styles.errorIcon}>
    //       <Popover
    //         title="表单校验信息"
    //         content={errorList}
    //         overlayClassName={styles.errorPopover}
    //         trigger="click"
    //         getPopupContainer={trigger => trigger.parentNode}
    //       >
    //         <Icon type="exclamation-circle" />
    //       </Popover>
    //       {errorCount}
    //     </span>
    //   );
    // };
    if (JSON.stringify(this.props.location.query) !== '{}') {
      return (
        <PageHeaderLayout
          title=""
          wrapperClassName={styles.advancedForm}
        >
          <Card title="" className={styles.card} bordered={false}>
            <Form layout="vertical" hideRequiredMark ref={this.formRef}>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.deviceId} name='deviceId' required rules={[{ required: true, message: '请输入设备ID' }]}>
                    
                      <Input maxLength="20" placeholder="请输入设备ID" disabled />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.iccid} name='iccid' required rules={[{ required: true, message: '请输入ICCID' }]}>
                    
                      <Input maxLength="20" placeholder="请输入ICCID" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.msisdn} name='msisdn' required rules={[{ required: true, message: '请输入MSISDN' }]}>
                    
                      <Input maxLength="20" placeholder="请输入MSISDN" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.carrierBrand} name='carrierBrand' rules={[{ required: false, message: '请选择运营商品牌' }]}>
                    
                      <Select allowClear placeholder="请选择运营商品牌" options={carrierBrandOptions}>
                      </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.simModel} name='simModel' rules={[{ required: false, message: '请选择套餐类型' }]}>
                   
                    <Select allowClear placeholder="请选择套餐类型" options={simModelOptions}>
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.unicomPkgId} name='unicomPkgId' rules={[{ required: false, message: '请输入联通套餐ID' }]}>
                    
                      <Input placeholder="请输入联通套餐ID" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.payType} name='payType' rules={[{ required: false, message: '请选择支付类型' }]}>
                    
                      <Select allowClear placeholder="请选择支付类型" options={payTypeOptions}>
                      </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.purchaser} name='purchaser' rules={[{ required: false, message: '请选择采购商' }]}>
                    
                      <Select allowClear placeholder="请选择采购商" options={purchaserOptions}>
                      </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.simStatus} name='simStatus' rules={[{ required: false, message: '请选择状态' }]}>
                  
                      <Select allowClear placeholder="请选择状态" options={simStatusOptions}>
                      </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.activeTime} name='activeTime' rules={[{ required: false, message: '激活时间' }]}>
                    
                      <Input placeholder="激活时间" disabled />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.produceDate} name='produceDate' rules={[{ required: false, message: '生产日期' }]}>
                   
                      <Input placeholder="生产日期" disabled />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.remark} name='remark' rules={[{ required: false, message: '请输入备注' }]}>
                   
                      <Input placeholder="请输入备注" />
                  </Form.Item>
                </Col>
              </Row>
              <Col >
                <Form.Item style={{ display: 'none' }} label="" name='sid'><Input /></Form.Item>
              </Col>
            </Form>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <div >
                    {/* {getErrorInfo()} */}
                    <Button loading={buttonLoading} key="submit" type="primary" size="default" onClick={validate}>
                      提交
                    </Button>
                    &nbsp;&nbsp;
                    <Popconfirm title="确定放弃修改吗?" onConfirm={() => this.canceledit()}>
                      <Button key="back" size="default">
                        取消
                      </Button>
                    </Popconfirm>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        </PageHeaderLayout>
      );
    } else {
      return (
        <PageHeaderLayout
          title=""
          wrapperClassName={styles.advancedForm}
        >
          <Card title="" className={styles.card} bordered={false}>
            <Form layout="vertical" hideRequiredMark ref={this.formRef}>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.projectId} name='projectId' required rules={[{ required: true, message: '请输入项目号' }]}>
                    <Select allowClear placeholder="请选择项目">
                      {projectIdData}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.deviceId} name='deviceId' required rules={[{ required: true, message: '请输入设备ID' }]}>
                   
                      <Input maxLength="20" placeholder="请输入设备ID" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.iccid} name='iccid' required rules={[{ required: true, message: '请输入ICCID' }]}>
                    
                      <Input maxLength="20" placeholder="请输入ICCID" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.msisdn} name='msisdn' required rules={[{ required: true, message: '请输入MSISDN' }]}>
                   
                    <Input maxLength="20" placeholder="请输入MSISDN" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.carrierBrand} name='carrierBrand' rules={[{ required: false, message: '请选择运营商品牌' }]}>
                   
                    <Select allowClear placeholder="请选择运营商品牌" options={carrierBrandOptions}>
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.simModel} name='simModel' rules={[{ required: false, message: '请选择套餐类型' }]}>
                   
                    <Select allowClear placeholder="请选择套餐类型" options={simModelOptions}>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.unicomPkgId} name='unicomPkgId' rules={[{ required: false, message: '请输入联通套餐ID' }]}>
                    
                      <Input placeholder="请输入联通套餐ID" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.payType} name='payType' rules={[{ required: false, message: '请选择支付类型' }]}>
                    
                    <Select allowClear placeholder="请选择支付类型" options={payTypeOptions}>
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.purchaser} name='purchaser' rules={[{ required: false, message: '请选择采购商' }]}>
          
                      <Select allowClear placeholder="请选择采购商" options={purchaserOptions}>
                      </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.simStatus} name='simStatus' rules={[{ required: false, message: '请选择状态' }]}>
                    
                    <Select allowClear placeholder="请选择状态" options={simStatusOptions}>
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.activeTime} name='activeTime' rules={[{ required: false, message: '激活时间' }]}>
                  
                      <DatePicker
                        style={{ width: '100%' }}
                        placeholder="请输入激活时间"
                        showTime
                        format="YYYY-MM-DD HH:mm:ss"
                      />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.produceDate} name='produceDate' rules={[{ required: false, message: '生产日期' }]}>
                    
                      <DatePicker
                        style={{ width: '100%' }}
                        showTime
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请输入生产日期"
                      />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item label={fieldLabels.remark} name='remark' rules={[{ required: false, message: '请输入备注' }]}>
                    
                      <Input placeholder="请输入备注" />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <div >
                    <Button loading={buttonLoading} key="submit" type="primary" size="default" onClick={validate}>
                      提交
                    </Button>
                    &nbsp;&nbsp;
                    <Popconfirm title="确定放弃添加吗?" onConfirm={() => this.props.history.goBack()}>
                      <Button key="back" size="default">
                        取消
                      </Button>
                    </Popconfirm>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
          <FooterToolbar />
        </PageHeaderLayout>
      );
    }
  }
}
